import Taro from "@tarojs/taro";

const FS = Taro.getFileSystemManager();

interface IFileResult {
  success: boolean;
  error?: { errMsg: string };
}

interface IReadFileResult extends IFileResult {
  data?: string | ArrayBuffer;
}

/**
 * 读取文件
 * @param filename
 * @returns
 */
export const readFile = async (filename: string): Promise<IReadFileResult> => {
  return new Promise((resolve, reject) => {
    FS.readFile({
      filePath: filename,
      encoding: "utf8",
      success(res) {
        resolve({ success: true, data: res.data });
      },
      fail(error) {
        resolve({ success: false, error });
      },
    });
  });
};

/**
 * 判断文件/目录是否存在
 * @param path
 * @returns
 */
export const exists = (path: string): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    FS.access({
      path,
      success(res) {
        if (res.errMsg === 'access:ok') {
          resolve(true)
        } else {
          resolve(false)
        }
      },
      fail() {
        resolve(false)
      }
    });
  });
}

/**
 * 写文件
 * @param fileName
 * @param data
 * @returns
 */
export const writeFile = (fileName: string, data: string | ArrayBuffer): Promise<IFileResult> => {
  return new Promise((resolve, reject) => {
    FS.writeFile({
      filePath: fileName,
      data,
      encoding: 'utf8',
      success(res) {
        resolve({ success: true, ...res });
      },
      fail(error) {
        resolve({ success: false, ...error });
      }
    });
  });
}
